package com.athenaeum.dataxplore.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.athenaeum.datastore.domain.NavigationUser;
import com.athenaeum.datastore.domain.Project;
import com.athenaeum.datastore.domain.User;
import com.athenaeum.datastore.service.ProjectService;
import com.athenaeum.datastore.service.UserService;
import com.athenaeum.datastore.util.UserUtil;

public class NavigationUserInterceptor extends HandlerInterceptorAdapter {

	private static final Logger log = LoggerFactory
			.getLogger(NavigationUserInterceptor.class);

	@Autowired
	private UserService userService;

	@Autowired
	private ProjectService projectService;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null) {
			log.debug("Adding user object to the model for view.");
			User user = userService.findOne(UserUtil.getUsernameInContext());
			NavigationUser navigationUser = new NavigationUser();
			Map<String, Object> attributes = new HashMap<String, Object>();
			navigationUser.setId(user.getId());
			navigationUser.setFullName(user.getFullName());
			for (Project project : user.getProjects().values()) {
				// TODO Replace the project with the value from MRU List.
				navigationUser.setCurrentProject(project);
			}
			attributes.put("unsavedFilterSize", 2);
			navigationUser.setAttributes(attributes);
			modelAndView.addObject("navigationUser", navigationUser);
		}
	}
}
